package com.sinodata.bsm.cicp.finder;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * <p>
 * Description: 简单的正则shell匹配发现
 * </p>
 *
 * @author Administrator
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-1-8 上午11:24:57          Administrator        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class RegexMatchShellFinder extends Finder {
    private static Logger logger = Logger.getLogger(RegexMatchShellFinder.class);

    @SuppressWarnings("rawtypes")
    @Override
    public List<String[]> find(String ip, Map params) {
        String environment = (String) params.get("ENV");
        String shell = (String) params.get("SHELL");
        String hostType = CommandReader.getHostType(ip);
        if (environment == null || environment.trim().length() == 0) {
            if (hostType != null) {
                shell = (hostType.equalsIgnoreCase("Linux") ? ". ./.bash_profile;" : ". ./.profile;") + shell;
            }
        } else {
            shell = environment + ";" + shell;
        }
        if (shell == null) {
            logger.error("RegexMatchShellFinder has error:collectCmd is null");
            return null;
        }
        String regex = (String) params.get("REGEX");
        if (regex == null) {
            logger.error("RegexMatchShellFinder has error:regex is null");
            return null;
        }
        //id,name,desc为可选的参数，参数格式可以为1:$n，表示将regex匹配第n组作为id，name，desc
        //                                      2:直接写不包含$n的字符串，则将对应字符串直接赋值
        //                                      3:如果为空表示将第一组赋值给id,name,desc
        String idStr = (String) params.get("ID");
        String nameStr = (String) params.get("NAME");
        String descStr = (String) params.get("DESC");
        int idInt = analysisArg(idStr);
        int nameInt = analysisArg(nameStr);
        int descInt = analysisArg(descStr);
        List<String[]> list = new ArrayList<String[]>();
        Pattern pattern = Pattern.compile(regex);
        int groupCount = pattern.matcher("").groupCount();
        BufferedReader reader = null;
        String strLine = null;
        try {
            reader = CommandReader.getReader(ip, shell, 0, 0);
            while ((strLine = reader.readLine()) != null) {
                strLine = strLine.trim();
                Matcher matcher = pattern.matcher(strLine);
                if (matcher.find()) {
                    String[] attrs = new String[groupCount + 3];
                    list.add(attrs);
                    attrs[0] = idInt > 0 ? (ip + matcher.group(idInt)) : idStr;
                    attrs[1] = nameInt > 0 ? matcher.group(nameInt) : nameStr;
                    attrs[2] = descInt > 0 ? (ip + matcher.group(descInt)) : descStr;
                    for (int i = 0; i < groupCount; i++) {
                        attrs[3 + i] = matcher.group(i + 1);
                    }
                }
            }
            return list;
        } catch (IOException e) {
            logger.error("failed to execute RegexMatchShellFinder:ip[" + ip + "],shell[" + shell + "],regex[" + regex + "]", e);
        }
        return null;
    }

    /**
     * 解析id,name,desc
     * @param args
     * @return
     */
    private int analysisArg(String arg) {
        if (arg == null) {
            return 1;
        }
        Matcher matcher = Pattern.compile("\\$(\\d+)").matcher(arg.trim());
        if (matcher.find()) {
            return Integer.parseInt(matcher.group(1));
        }
        return -1;
    }
}
